from flask import render_template, redirect, url_for, escape,request
from . import main_bp
from .forms import QuestionnaireForm
from ..models import Questionnaire, db
from multiprocessing import Value

counter = Value('i', 0)
counter2 = Value('i', 0)

@main_bp.before_request
def add_counter():
    with counter.get_lock():
        # Count how many people has been to the website
        counter.value += 1
    print(counter.value)


@main_bp.route('/', methods=['GET', 'POST'])
def questionnaire():
    form = QuestionnaireForm()
    if form.validate_on_submit():
        questionnaire = Questionnaire(
            q1=form.q1.data,
            q2=form.q2.data,
            q3=form.q3.data,
            q4=form.q4.data,
            q5=form.q5.data,
            q6=form.q6.data,
            q7=form.q7.data,
            q8=form.q8.data,
            q9=form.q9.data
        )
        db.session.add(questionnaire)
        db.session.commit()
        return redirect(url_for('.thanks', from_url=escape(url_for('.questionnaire'))))
    return render_template('questionnaire.html', form=form)


@main_bp.route('/thanks', methods=['GET'])
def thanks():
    from_url = request.args.get('from_url', None)
    if from_url == url_for('.questionnaire'):
        with counter2.get_lock():
            # Count how mant people has taken the questionnaire
            counter2.value += 1
    return render_template('thanks.html')
